﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base.Tools;

namespace TrinityAPI.Base
{
    public class SendEmail : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var request = args.Length > 0 ? args[0] as JObject : dataset.GetJsonObject("request");
            var constant = dataset.GetJsonObject("constant");
            var emailAlert = constant.GetJsonObject("emailAlert") ?? constant.GetJsonObject("emailAlter"); //Alert错误拼写成Alter，兼容处理

            string environment = emailAlert.GetJsonObjectStringValue("environment");
            string host = emailAlert.GetJsonObjectStringValue("host");
            string username = emailAlert.GetJsonObjectStringValue("username");
            string password = emailAlert.GetJsonObjectStringValue("password");
            string domain = emailAlert.GetJsonObjectStringValue("domain");
            string sender = emailAlert.GetJsonObjectStringValue("sender");
            bool isAsync = emailAlert.GetJsonObjectBooleanValue("isAsync");

            var Attachments = new Dictionary<string, byte[]>();
            string subject = request.GetJsonObjectStringValue("subject");
            string message = request.GetJsonObjectStringValue("message");
            string receiver = request.GetJsonObjectStringValue("receiver", emailAlert.GetJsonObjectStringValue("receiver"));
            string cc = request.GetJsonObjectStringValue("cc", emailAlert.GetJsonObjectStringValue("cc"));
            string bcc = request.GetJsonObjectStringValue("bcc", emailAlert.GetJsonObjectStringValue("bcc"));
            var attachments = request.GetJsonObject("attachments");
            if (attachments != null)
            {
                foreach (var item in attachments)
                {
                    try
                    {
                        if (item.Value?.Type == JTokenType.Bytes)
                        {
                            Attachments.Add(item.Key, item.Value.Value<byte[]>());
                        }
                        else if (item.Value?.Type == JTokenType.String)
                        {
                            string value = item.Value.ToString();
                            if (!System.IO.Path.IsPathRooted(value) || value.StartsWith("/") || value.StartsWith("\\"))
                                value = Utils.GetMapPath(value);
                            if (System.IO.Path.IsPathRooted(value) && System.IO.File.Exists(value))
                            {
                                Attachments.Add(item.Key, Utils.GetBytesFromFile(value));
                                continue;
                            }

                            Attachments.Add(item.Key, Convert.FromBase64String(value));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Warn("Parse email attachment error", ex);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(environment))
                subject += "-" + environment;

            if (isAsync)
            {
                System.Threading.ThreadPool.UnsafeQueueUserWorkItem(new System.Threading.WaitCallback(o =>
                {
                    Utils.SendEmail(subject, message, receiver, sender, host, username, password, domain, true, cc, bcc, Attachments);
                }), null);
            }
            else
            {
                Utils.SendEmail(subject, message, receiver, sender, host, username, password, domain, true, cc, bcc, Attachments);
            }

            return true;
        }
    }
}
